package com.yyryyty.chapter4;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

public class StreamBasic {

    public static void main(String... args) {
        // Java 7
//        getLowCaloricDishesNamesInJava7(Dish.menu).forEach(System.out::println);
//
//        System.out.println("---");

        // Java 8
//        getLowCaloricDishesNamesInJava8(Dish.menu).forEach(System.out::println);

        // Test 1
//        System.out.println(Dish.menu.stream()
//                // 热量大于300
//                .filter(dish -> dish.getCalories() > 300)
//                .sorted(comparing(Dish::getCalories).reversed())
//                //
//                .limit(3)
//                .map(Dish::getName)
//                .collect(toList()));

//        Stream<Dish> stream = Dish.menu.stream();
//
//        Stream<String> stream1 = stream
//                .map(Dish::getName);
//
//        stream1.forEach(System.out::println);
//        stream1.forEach(System.out::println);

        System.out.println(Dish.menu.stream()
                .filter(dish -> dish.getCalories() > 300)
                .sorted(comparing(Dish::getCalories).reversed())
                .limit(6)
                .map(dish -> dish.getType().toString())
                .distinct()
                .count());

    }

    public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes) {
        List<Dish> lowCaloricDishes = new ArrayList<>();
        for (Dish d : dishes) {
            if (d.getCalories() < 400) {
                lowCaloricDishes.add(d);
            }
        }
        List<String> lowCaloricDishesName = new ArrayList<>();
        Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
            public int compare(Dish d1, Dish d2) {
                return Integer.compare(d1.getCalories(), d2.getCalories());
            }
        });
        for (Dish d : lowCaloricDishes) {
            lowCaloricDishesName.add(d.getName());
        }
        return lowCaloricDishesName;
    }

    public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes) {

        return dishes.stream()
                //筛选卡路里大于400
                .filter(dish -> dish.getCalories() > 400)
                //卡路里降序排序
                .sorted(comparing(Dish::getCalories).reversed())
                //提取菜肴类型
                .map(dish -> dish.getType().toString())
                //去重
                .distinct()
                //跳过第一个
                .skip(1)
                //转List
                .collect(toList());
    }
}
